package com.chenyongjing.design.pattern.proxy.dynamicUsualProxy;

import com.chenyongjing.design.pattern.proxy.dynamicProxy.Rent;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 自动生成代理类
 */
public class ProxyInvocationHandler implements InvocationHandler {
    /**
     * 被代理接口
     */
    public Object target;

    public void setRent(Object target){
        this.target = target;
    }

    /**
     * 生成代理类
     * @return
     */
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }

    /**
     * 处理代理实例并返回结果
     * @param proxy the proxy instance that the method was invoked on
     *
     * @param method the {@code Method} instance corresponding to
     * the interface method invoked on the proxy instance.  The declaring
     * class of the {@code Method} object will be the interface that
     * the method was declared in, which may be a superinterface of the
     * proxy interface that the proxy class inherits the method through.
     *
     * @param args an array of objects containing the values of the
     * arguments passed in the method invocation on the proxy instance,
     * or {@code null} if interface method takes no arguments.
     * Arguments of primitive types are wrapped in instances of the
     * appropriate primitive wrapper class, such as
     * {@code java.lang.Integer} or {@code java.lang.Boolean}.
     *
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 动态代理的本质，使用反射机制实现
        log(method.getName());
        Object  result = method.invoke(target,args);
        return result;
    }

    /**
     * 新增的日志方法
     */
    public void log(String msg){
        System.out.println("执行了"+msg+"方法");
    }
}
